<?php
/**
 * admin service file Created by PhpStorm.
 * User: yang
 * Date: 2020/04/26
 */

namespace App\Http\Service\Admin;

use Common\Repository\PowerRepository;
use Common\Repository\RolesRepository;
use Common\Repository\RolesPowerRepository;

class RolesService
{
    /**
     * 获取全部
     *
     * @return array
     */
    public function getAll()
    {
        try {
            $arr_option['where'] = ['status' => 0];
            $arr_option['field'] = ['id', 'name', 'display'];

            $result = RolesRepository::getAll($arr_option);

            if ($result) {
                return hello_success('获取成功！', $result);
            }

            return hello_error('获取失败！');
        } catch (\Exception $exception) {
            return hello_error('失败！', $exception->getMessage());
        }
    }

    /**
     * 获取列表
     *
     * @param array $get_data
     * @return array
     */
    public function getList($get_data = [])
    {
        try {
            if (isset($get_data['field']) && isset($get_data['order'])) {
                $arr_option['order'] = ['key' => $get_data['field'], 'value' => $get_data['order']];
            }
            $arr_option['limit'] = $get_data['limit'];
            $arr_option['where'] = $get_data['where'];

            $result = RolesRepository::getList($arr_option);
            $list = list_data_page($result, $get_data);

            return $list;
        } catch (\Exception $exception) {
            return hello_error('失败！', $exception->getMessage());
        }
    }

    /**
     * 添加操作
     *
     * @param array $post_data
     * @return array
     */
    public function insert($post_data = [])
    {
        try {
            $result = RolesRepository::addOne($post_data);

            if ($result) {
                return hello_success('添加成功！', $result);
            }

            return hello_error('添加失败！');
        } catch (\Exception $exception) {
            return hello_error('失败！', $exception->getMessage());
        }
    }

    /**
     * 编辑视图
     *
     * @param int $id
     * @return array
     */
    public function edit(int $id)
    {
        try {
            if ($id == 0) {
                error_prompt('参数错误');
            }
            $result = RolesRepository::findOne($id);

            if ($result) {
                return hello_success('获取成功！', $result);
            }

            return hello_error('获取失败！');
        } catch (\Exception $exception) {
            return hello_error('失败！', $exception->getMessage());
        }
    }

    /**
     * 编辑操作
     *
     * @param array $post_data
     * @return array
     */
    public function update($post_data = [])
    {
        try {
            $result = RolesRepository::editOne($post_data);

            if ($result) {
                return hello_success('编辑成功！', $result);
            }

            return hello_error('编辑失败！');
        } catch (\Exception $exception) {
            return hello_error('失败！', $exception->getMessage());
        }
    }

    /**
     * 删除操作
     *
     * @param int $id
     * @return array
     */
    public function delete(int $id)
    {
        try {
            if ($id == 0) {
                error_prompt('参数错误');
            }
            //检测该角色是否有用户
            $find = self::checkIsHaveAdmin($id);
            if ($find['code'] == 1) {
                return $find;
            }

            $result = RolesRepository::deleteOne($id);

            if ($result) {
                return hello_success('删除成功！', $result);
            }

            return hello_error('删除失败失败！');
        } catch (\Exception $exception) {
            return hello_error('失败！', $exception->getMessage());
        }
    }

    /**修改状态
     *
     * @param array $post_data
     * @return array
     */
    public function editStatus($post_data = [])
    {
        try {
            $id = $post_data['id'] ?? 0;
            if ($id == 0) {
                return hello_error('参数错误');
            }

            //检测该角色是否有用户
            /*if ($post_data['status'] == 0) {
                $find = self::checkIsHaveAdmin($id);
                if ($find['code'] == 1) {
                    return $find;
                }
            }*/

            $up_status = [
                'id' => $post_data['id'],
                'status' => $post_data['status'] == 1 ? 0 : 1
            ];

            $result = RolesRepository::editOne($up_status);

            if ($result) {
                return hello_success('修改成功！', $up_status['status']);
            }

            return hello_error('修改失败！');
        } catch (\Exception $exception) {
            return hello_error('失败！', $exception->getMessage());
        }
    }

    /**
     * 检测该角色是否有用户
     * @param int $role_id
     * @return array
     */
    public function checkIsHaveAdmin(int $role_id)
    {
        $find_where = ['role' => $role_id];
        $num = \Common\Repository\PublicRepository::countNum('Admin', $find_where);

        if ($num > 0) {
            return hello_error('该角色已被使用，不能删除！');
        }

        return hello_success('Ok！');
    }

    /**
     * 获取树形数据
     *
     * @return array
     */
    public function getPowerList($id = null)
    {
        try {
            //获取该角色现有的权限
            $map['where']['roles_id'] = $id;
            $power = RolesPowerRepository::extendGetAll($map);
            $powerIds = array_column($power, 'power_id');

            $arr_option['field'] = ['id', 'pid', 'name'];
            $arr_option['order'] = ['key'=>'sort', 'value'=> 'asc'];
            $result = PowerRepository::getAll($arr_option);
            $tree = [];
            foreach ($result as $key => $item) {
                $tree[$key]['id'] = $item['id'];
                $tree[$key]['pid'] = $item['pid'];
                $tree[$key]['title'] = $item['name'];
                if(in_array($item['id'], $powerIds)){
                    $tree[$key]['checked'] = true;
                }
            }

            $data = makeTree($tree);

            return hello_success('Ok！', $data);
        } catch (\Exception $exception) {
            return hello_error('失败！', $exception->getMessage());
        }
    }

    /**
     * 权限操作
     * @param array $post_data
     * @return array
     */
    public function power($post_data = [])
    {
        try {
            $id = $post_data['id'];
            if ($post_data['power']) {
                $roles_power = [];
                foreach ($post_data['power'] as $item) {
                    $roles_power[] = [
                        'roles_id' => $id,
                        'power_id' => $item
                    ];
                }
                //删除原有数据
                RolesPowerRepository::deleteByWhere(['roles_id' => $id], true);
                $result = RolesPowerRepository::addMany($roles_power);
                if ($result) {
                    return hello_success('修改成功！', $result);
                }
            }else{
                return hello_error('请勾选权限！');
            }

            return hello_error('参数错误！');
        } catch (\Exception $exception) {
            return hello_error('失败！', $exception->getMessage());
        }
    }
}